﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GestionWeb.Models;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using GestionWeb.Excepciones;
using System.Text;


namespace GestionWeb.Controllers
{
    public class MovimientoController : Controller
    {
        private List<Movimiento> IngresoFill()
        {
            List<Movimiento> det = new List<Movimiento>();

            return det;
        }


        private List<MovDetalle> ObtenerDetalleIngreso(int idped, int idmov)
        {

            HttpWebRequest req2 = (HttpWebRequest)WebRequest.
                Create("http://localhost:50310/Movimientos.svc/PedidosIngreso/" + idped);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string pedidoJson = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            Pedido pedidoObtenido = js2.Deserialize<Pedido>(pedidoJson);

            Movimiento movimiento = new Movimiento() { idmov = idmov, tipmov = "EN", idped = pedidoObtenido.idpedido, fecMov = DateTime.Today };


            HttpWebRequest req = (HttpWebRequest)WebRequest.
           Create("http://localhost:50310/Movimientos.svc/PedidoDetalles/" + idped);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string detalleJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<PedidoDetalle> detalleLista = js.Deserialize<List<PedidoDetalle>>(detalleJson);

            List<MovDetalle> mov = new List<MovDetalle>();
            PedidoDetalle detalleLine = new PedidoDetalle();

            decimal cantidad;
            int ipos;
            string pos;

            for (int i = 0; i < detalleLista.Count; i++) // Loop through List with for
            {
                ipos = (i + 1) * 10;
                pos = ipos.ToString();
                cantidad = detalleLista[i].cantped - detalleLista[i].cantent;
                ProductosMS.Producto producto = new ProductosMS.Producto() { Codigo = detalleLista[i].producto.Codigo, Denominacion = detalleLista[i].producto.Denominacion };
                Centro centro = new Centro() { idCentro = detalleLista[i].centro.idCentro, denCentro = detalleLista[i].centro.denCentro };
                mov.Add(new MovDetalle()
                {
                    idmov = idmov,
                    pos = pos,
                    cant = cantidad,
                    idprod = detalleLista[i].idprod,
                    movcab = movimiento,
                    producto = producto,
                    centro = centro
                });
            }

            return mov;
        }

        private List<MovDetalle> GetDetalle(int idped, int idmov)
        {

            HttpWebRequest req2 = (HttpWebRequest)WebRequest.
                Create("http://localhost:50310/Movimientos.svc/PedidosSalida/" + idped);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string pedidoJson = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            Pedido pedidoObtenido = js2.Deserialize<Pedido>(pedidoJson);

            Movimiento movimiento = new Movimiento() { idmov = idmov, tipmov = "SA", idped = pedidoObtenido.idpedido, fecMov = DateTime.Today };


            HttpWebRequest req = (HttpWebRequest)WebRequest.
           Create("http://localhost:50310/Movimientos.svc/PedidoDetalles/" + idped);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string detalleJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<PedidoDetalle> detalleLista = js.Deserialize<List<PedidoDetalle>>(detalleJson);

            List<MovDetalle> mov = new List<MovDetalle>();
            PedidoDetalle detalleLine = new PedidoDetalle();

            decimal cantidad;
            int ipos;
            string pos;

            for (int i = 0; i < detalleLista.Count; i++) // Loop through List with for
            {
                ipos = (i + 1) * 10;
                pos = ipos.ToString();
                cantidad = detalleLista[i].cantped - detalleLista[i].cantent;
                //  Producto producto = new Producto() { idProducto = detalleLista[i].producto.Codigo, noProducto = detalleLista[i].producto.Denominacion };
                ProductosMS.Producto producto = new ProductosMS.Producto() { Codigo = detalleLista[i].producto.Codigo, Denominacion = detalleLista[i].producto.Denominacion };
                Centro centro = new Centro() { idCentro = detalleLista[i].centro.idCentro, denCentro = detalleLista[i].centro.denCentro };
                mov.Add(new MovDetalle()
                {
                    idmov = idmov,
                    pos = pos,
                    cant = cantidad,
                    idprod = detalleLista[i].idprod,
                    movcab = movimiento,
                    cantorig = cantidad,
                    producto = producto,
                    centro = centro
                });
            }

            return mov;
        }

        private MovDetalle SeleccionarPos(string pos)
        {
            List<MovDetalle> detalleMov = (List<MovDetalle>)Session["salida"];
            MovDetalle model = detalleMov.Single(delegate(MovDetalle det)
            {
                if (det.pos == pos)
                    return true;
                else
                    return false;
            });
            return model;
        }

        private MovDetalle SeleccionarPosIngreso(string pos)
        {
            List<MovDetalle> detalleMov = (List<MovDetalle>)Session["Ingreso"];
            MovDetalle model = detalleMov.Single(delegate(MovDetalle det)
            {
                if (det.pos == pos)
                    return true;
                else
                    return false;
            });
            return model;
        }

        public ActionResult EditarIngreso(string pos)
        {
            MovDetalle model = SeleccionarPosIngreso(pos);
            return View(model);
        }

        [HttpPost]
        public ActionResult EditarIngreso(string pos, FormCollection collection)
        {
            try
            {

                MovDetalle model = SeleccionarPosIngreso(pos);
                model.cant = Decimal.Parse(collection["cant"].ToString());
                model.txtPos = collection["txtPos"];
                List<MovDetalle> model1 = (List<MovDetalle>)Session["Ingreso"];

                return View("DetalleIngreso", model1);
            }
            catch
            {
                return View();
            }
        }

        // GET: /Ingreso/RegistrarIngreso

        public ActionResult RegistrarIngreso()
        {
            return View();
        }

        public ActionResult DetalleIngreso(int id)
        {
            return View();
        }



        public ActionResult EditCant(string pos)
        {
            MovDetalle model = SeleccionarPos(pos);
            return View(model);

        }


        public ActionResult DetalleSalida(int id)
        {
            return View();
        }

        [HttpPost]

        public ActionResult DetalleSalida(FormCollection collection)
        {
            List<MovDetalle> items = (List<MovDetalle>)Session["salida"];

            Movimiento movACrear;
            Movimiento movCreado = null;

            try
            {

                string postdata = "";


                // primero se validará que exista stock suficiente

                for (int i = 0; i < items.Count; i++)
                {
                    try
                    {
                        HttpWebRequest req2 = (HttpWebRequest)WebRequest.
                  Create("http://localhost:50310/Movimientos.svc/Stocks/" + items[i].centro.idCentro + "," + items[i].producto.Codigo);
                        req2.Method = "GET";
                        HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
                        StreamReader reader2 = new StreamReader(res2.GetResponseStream());
                        string stockJson = reader2.ReadToEnd();
                        JavaScriptSerializer js2 = new JavaScriptSerializer();
                        AlmacenProd stockObtenido = js2.Deserialize<AlmacenProd>(stockJson);

                        if (stockObtenido.Stock <= items[i].cant)
                        {

                            string cad = "No exite stock suficiente en el Centro  "
                                 + items[i].centro.idCentro + "-" + items[i].centro.denCentro +
                                 " para el producto " + items[i].producto.Codigo + "-" + items[i].producto.Denominacion;

                            throw new Exception(cad);
                            /*  throw new WebFaultException<Excepcion>(
                               new Excepcion()
                               {
                                   Mensaje = "No exite stock suficiente en el Centro  "
                                   + items[i].centro.idCentro + "-" + items[i].centro.denCentro +
                                   " para el producto " + items[i].producto.Codigo + "-" + items[i].producto.Denominacion
                               }, HttpStatusCode.InternalServerError);
                          */
                        }

                    }
                    catch (WebException e)
                    {
                        HttpWebResponse resError = (HttpWebResponse)e.Response;
                        StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                        string error = reader2.ReadToEnd();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        Excepcion Ex = js.Deserialize<Excepcion>(error);

                        //ModelState.AddModelError(String.Empty, e.Message);
                        ModelState.AddModelError(String.Empty, Ex.Mensaje);
                        return View();

                    }

                }


                /*++++++++++++++++++++Inicio de inserción de detalle del movimiento +++++++++++++++++++++++++++++++++++++++++*/

                for (int i = 0; i < items.Count; i++)
                {
                    if (i == 0)
                    {
                        movACrear = items[i].movcab;

                        try
                        {
                            postdata = "";
                            postdata = "{\"idmov\":" + movACrear.idmov + ",\"tipmov\":\"" + movACrear.tipmov + "\",\"idped\":" + movACrear.idped + "}"; //JSON  

                            byte[] data = Encoding.UTF8.GetBytes(postdata);

                            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:50310/Movimientos.svc/Salidas");
                            req.Method = "POST";
                            req.ContentLength = data.Length;
                            req.ContentType = "application/json";
                            var reqStream = req.GetRequestStream();
                            reqStream.Write(data, 0, data.Length);
                            var res = (HttpWebResponse)req.GetResponse();
                            StreamReader reader = new StreamReader(res.GetResponseStream());
                            string movJson = reader.ReadToEnd();
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            movCreado = js.Deserialize<Movimiento>(movJson);
                        }
                        catch (WebException e)
                        {
                            HttpWebResponse resError = (HttpWebResponse)e.Response;
                            StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                            string error = reader2.ReadToEnd();
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            Excepcion Ex = js.Deserialize<Excepcion>(error);

                            //ModelState.AddModelError(String.Empty, e.Message);
                            ModelState.AddModelError(String.Empty, Ex.Mensaje);
                            return View("RegistrarSalida");

                        }

                    }
                        MovDetalle ItemMovCreado = null;

                        try
                        {
                            string postdata2 = "{\"idmov\":" + items[i].idmov + ",\"pos\":\"" + items[i].pos + "\",\"idprod\":" + items[i].producto.Codigo + ",\"idcentro\":" + items[i].centro.idCentro + ",\"cant\":" + items[i].cant + ",\"txtPos\":\"" + items[i].txtPos + "\"" + "}"; //JSON  

                            byte[] dataitem = Encoding.UTF8.GetBytes(postdata2);

                            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://localhost:50310/Movimientos.svc/SalidaItems");
                            req2.Method = "POST";
                            req2.ContentLength = dataitem.Length;
                            req2.ContentType = "application/json";
                            var reqStream2 = req2.GetRequestStream();
                            reqStream2.Write(dataitem, 0, dataitem.Length);
                            var res2 = (HttpWebResponse)req2.GetResponse();
                            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
                            string ItemMovJson = reader2.ReadToEnd();
                            JavaScriptSerializer js2 = new JavaScriptSerializer();
                            ItemMovCreado = js2.Deserialize<MovDetalle>(ItemMovJson);

                        }
                        catch (WebException e)
                        {
                            HttpWebResponse resError = (HttpWebResponse)e.Response;
                            StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                            string error = reader2.ReadToEnd();
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            Excepcion Ex = js.Deserialize<Excepcion>(error);

                            //ModelState.AddModelError(String.Empty, e.Message);
                            ModelState.AddModelError(String.Empty, Ex.Mensaje);
                            return View("RegistrarSalida");

                        }

                  

                }

                return View("RegistrarSalida");
            }
            catch (WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Excepcion Ex = js.Deserialize<Excepcion>(error);

                //ModelState.AddModelError(String.Empty, e.Message);
                ModelState.AddModelError(String.Empty, Ex.Mensaje);
                return View("RegistrarSalida");

            }
            catch (Exception e)
            {
                ModelState.AddModelError(String.Empty, e.Message);
                return View(items);
            }
        }



        //
        // POST: /Ingreso/RegistrarIngreso
        [HttpPost]
        public ActionResult EditCant(string pos, FormCollection collection)
        {
            string msg = "";
            try
            {

                MovDetalle model = SeleccionarPos(pos);
                if (Decimal.Parse(collection["cant"].ToString()) > model.cantorig)
                {
                    string cad = "Cantidad ingresada es mayor a la cantidad pendiente. Cantidad pendiente: " +
                               model.cant;

                    throw new Exception(cad);
                }
                if (Decimal.Parse(collection["cant"].ToString()) == 0 )
                {
                    string cad = "Cantidad ingresada es 0. No es valor permitido";

                    throw new Exception(cad);
                }
                model.cant = Decimal.Parse(collection["cant"].ToString());
                model.txtPos = collection["txtPos"];
                List<MovDetalle> model1 = (List<MovDetalle>)Session["salida"];

                return View("DetalleSalida", model1);
            }
            catch (Exception e)
            {
                ModelState.AddModelError(String.Empty, e.Message);
                MovDetalle model = SeleccionarPos(pos);
                return View(model);

            }
        }

        [HttpPost]
        public ActionResult RegistrarIngreso(FormCollection collection)
        {

            try
            {
                int idped = int.Parse(collection["idped"]);
                int idmov = int.Parse(collection["idmov"]);

                Session["Ingreso"] = ObtenerDetalleIngreso(idped, idmov);
                List<MovDetalle> model = (List<MovDetalle>)Session["Ingreso"];

                return View("DetalleIngreso", model);
            }
            catch (WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Excepcion Ex = js.Deserialize<Excepcion>(error);

                //ModelState.AddModelError(String.Empty, e.Message);
                ModelState.AddModelError(String.Empty, Ex.Mensaje);
                return View();
            }
        }


        public ActionResult RegistrarSalida()
        {
            return View();
        }
        //
        // POST: /Movimiento/RegistrarSalida

        [HttpPost]
        public ActionResult RegistrarSalida(FormCollection collection)
        {
            try
            {
                int idped = int.Parse(collection["idped"]);
                int idmov = int.Parse(collection["idmov"]);
                //  if (Session["salida"] == null)
                Session["salida"] = GetDetalle(idped, idmov);
                List<MovDetalle> model = (List<MovDetalle>)Session["salida"];

                return View("DetalleSalida", model);
            }
            catch (WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Excepcion Ex = js.Deserialize<Excepcion>(error);

                //ModelState.AddModelError(String.Empty, e.Message);
                ModelState.AddModelError(String.Empty, Ex.Mensaje);
                return View();
            }


        }



        public ActionResult DeleteSalida(string pos)
        {
            MovDetalle model = SeleccionarPos(pos);
            return View(model);
        }

        [HttpPost]
        public ActionResult DeleteSalida(string pos, FormCollection collection)
        {
            try
            {
                List<MovDetalle> items = (List<MovDetalle>)Session["salida"];
                items.Remove(SeleccionarPos(pos));

                return View("DetalleSalida", items);
            }
            catch
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult DetalleIngreso(FormCollection collection)
        {
            List<MovDetalle> items = (List<MovDetalle>)Session["Ingreso"];

            Movimiento movACrear;
            Movimiento movCreado = null;



            string postdata = "";
        

            byte[] data = Encoding.UTF8.GetBytes(postdata);

            for (int i = 0; i < items.Count; i++)
            {
                if (i == 0)
                {
                    movACrear = items[i].movcab;

                    try
                    {
                        postdata = "";
                        postdata = "{\"idmov\":" + movACrear.idmov + ",\"tipmov\":\"" + movACrear.tipmov + "\",\"idped\":" + movACrear.idped + "}"; //JSON  

                        data = Encoding.UTF8.GetBytes(postdata);
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:50310/Movimientos.svc/Ingresos");
                        req.Method = "POST";
                        req.ContentLength = data.Length;
                        req.ContentType = "application/json";
                        var reqStream = req.GetRequestStream();
                        reqStream.Write(data, 0, data.Length);
                        var res = (HttpWebResponse)req.GetResponse();
                        StreamReader reader = new StreamReader(res.GetResponseStream());
                        string movJson = reader.ReadToEnd();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        movCreado = js.Deserialize<Movimiento>(movJson);
                    }
                    catch (WebException e)
                    {
                        HttpWebResponse resError = (HttpWebResponse)e.Response;
                        StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                        string error = reader2.ReadToEnd();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        Excepcion Ex = js.Deserialize<Excepcion>(error);
                        ModelState.AddModelError(String.Empty, Ex.Mensaje);
                        return View("RegistrarSalida");
                    }

                }
                    MovDetalle ItemMovCreado = null;

                    try
                    {
                        postdata = "{\"idmov\":" + items[i].idmov + ",\"pos\":\"" + items[i].pos + "\",\"idprod\":" + items[i].producto.Codigo + ",\"idcentro\":" + items[i].centro.idCentro + ",\"cant\":" + items[i].cant + ",\"txtPos\":\"" + items[i].txtPos + "\"" + "}"; //JSON  

                        data = Encoding.UTF8.GetBytes(postdata);

                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:50310/Movimientos.svc/IngresoItems");
                        req.Method = "POST";
                        req.ContentLength = data.Length;
                        req.ContentType = "application/json";
                        var reqStream = req.GetRequestStream();
                        reqStream.Write(data, 0, data.Length);
                        var res = (HttpWebResponse)req.GetResponse();
                        StreamReader reader = new StreamReader(res.GetResponseStream());
                        string ItemMovJson = reader.ReadToEnd();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        ItemMovCreado = js.Deserialize<MovDetalle>(ItemMovJson);
                    }
                    catch (WebException e)
                    {
                        HttpWebResponse resError = (HttpWebResponse)e.Response;
                        StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                        string error = reader2.ReadToEnd();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        Excepcion Ex = js.Deserialize<Excepcion>(error);

                        //ModelState.AddModelError(String.Empty, e.Message);
                        ModelState.AddModelError(String.Empty, Ex.Mensaje);
                        return View("RegistrarIngreso");
                    }
               
            }
            return View("RegistrarIngreso");
        } 
    }
}
